package leetcode;

/**
 * @author ht
 * @create 2025-06-18 20:10
 * @desc
 **/
public class T704 {

    //public int search(int[] nums, int target) {
    //    int l = 0;
    //    int r = nums.length;
    //    while(l <= r){ {
    //        int mid = (l + r) / 2;
    //        if(nums[mid] == target) {
    //            return mid;
    //        } else if(nums[mid] > target) {
    //            r = mid -1;
    //        } else {
    //            l = mid + 1;
    //        }
    //    }
    //    }
    //    return -1;
    //}

    /**
     * 左闭右闭写法
     * @param nums
     * @param target
     * @return
     */
    public int search(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        int mid = 0;
        while (left <= right) {
            mid = left + (right - left) / 2;
            if(nums[mid] > target) {
                // 目标数小于中位数，需要修改左区间的右边界
                // 由于是左闭右闭区间，因此mid属于右区间的合法区域，right应该从mid-1开始
                right = mid - 1;
            } else if(nums[mid] < target) {
                // 由于左区间是合法区间，因此左指针从left+1开始
                left = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    /**
     * 左闭右开写法
     * @param nums
     * @param target
     * @return
     */
        public int search2(int[] nums, int target) {
            int left = 0;
            int right = nums.length;
            int mid = 0;
            while (left < right) {
                mid = left + (right - left) / 2;
                if(nums[mid] > target) {
                    right = mid;
                } else if(nums[mid] < target) {
                    left = mid + 1;
                } else {
                    return mid;
                }
            }
            return -1;
        }
}
